package at.fhooe.tuxgestures.keysimulator;

import at.fhooe.tuxgestures.cam.mapper.event.StateChangeEvent;

//PAUSE_GAME: P=80 (the game resumes pressing any key...)
//MOVEMENT_RIGHT: D=68
//MOVEMENT_LEFT: A=65
//MOVEMENT_FORWARD: W=87
//MOVEMENT_BACKWARD: S=83
//ALT (key) = 18, I use this for the witch of tabs
public class KeySimulator implements IKeySimulator
{
	private Thread thread = null;
	private KeyProcess runnable = null;
	private int keyNumber;

	@Override
	public void stateChanged(StateChangeEvent event)
	{
		System.out.println("State changed to: " + event.getState());
		
		keyRelease();
		switch (event.getState()) {
		case MOVEMENT_FORWARD:
			//keyRelease();
			keyNumber = 87;
			keyPress(keyNumber);
			break;
		case MOVEMENT_BACKWARD:
			//keyRelease();
			keyNumber = 83;
			keyPress(keyNumber);
			break;
		case MOVEMENT_LEFT:
			//keyRelease();
			keyNumber = 65;
			keyPress(keyNumber);
			break;
		case MOVEMENT_RIGHT:
			//keyRelease();
			keyNumber = 68;
			keyPress(keyNumber);
			break;
		case SHOW_TUTORIAL:
			keyNumber = 0;
			keyPress(keyNumber);
			break;
		case SHOW_GAME:
			keyNumber = 1;
			keyPress(keyNumber);
			break;
		default:
			break;
		}
	}
	
	public void keyPress(int state) {
		runnable = new KeyProcess(state);
		thread = new Thread(runnable);
		thread.start();
	}
	
	public void keyRelease() {
		if (thread != null) {
			runnable.terminate();
			try {
				thread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}

